package com.wangyu.springsecuritydemo.config;

import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @Author wangyu
 * @Date 2019/2/21 18:09
 * @Version 1.0
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    //实体管理应用
    entityManagerFactoryRef = "entityManagerFactorySecondary",
    //事务管理应用
    transactionManagerRef = "transactionManagerSecondary",
    //设置主数据源所应用到的包
    basePackages = {"com.wangyu.springsecuritydemo.repository.secondary"}
)
public class SecondaryDataSourceConfig {

  @Autowired
  @Qualifier("secondaryDataSource")
  private DataSource secondaryDataSource;

  @Autowired(required = false)
  private JpaProperties jpaProperties;

  @Bean(name = "entityManagerSecondary")
  public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
    return entityManagerFactorySecondary(builder).getObject().createEntityManager();
  }

  @Bean("entityManagerFactorySecondary")
  public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
      EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(secondaryDataSource)
        .properties(getVendorProperties(secondaryDataSource))
        .packages("com.wangyu.springsecuritydemo.entity.secondary")
        .persistenceUnit("secondaryPersistenceUnit")
        .build();
  }

  private Map<String, String> getVendorProperties(DataSource dataSource) {
    return jpaProperties.getHibernateProperties(dataSource);
  }

  /**
   * 事务管理器：事务不能跨数据源，跨数据源，事务是不生效的。使用事务时，最好要指明使用哪个事务管理器，不然就会默认使用primary修饰的事务管理器
   */
  @Primary
  @Bean("transactionManagerSecondary")
  public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactorySecondary(builder).getObject());
    return txManager;
  }
}
